package cn.liufuwen.jpython;

import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "*",maxAge = 3600)
public class APIController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping("/post")
	public String post(@RequestParam(value="content",defaultValue="") String content){
		String filePath = "./python/py"+new Date().getTime()+".py";
		File file = new File(filePath);
		FileWriter fileWritter;
		List<String> stList = new ArrayList<String>();
		String st = "";
		try {
			if(!file.exists()){
	        	file.createNewFile();
	        }
			fileWritter = new FileWriter(file,false);
			fileWritter.write(content);
			fileWritter.flush();
			// 判断：若对象writer为空，则不会进行下一步操作，若不是空，则关闭流
			if (fileWritter != null) {
				// 关闭缓冲流时，也会刷新一次缓冲区
				fileWritter.close();
			}
			String[] arguments = new String[] {"python", filePath};
	        Process process = Runtime.getRuntime().exec(arguments); //执行一个系统命令 
	        String i = process.waitFor()==0?"成功":"失败";
			logger.info("执行结果："+ i);
	        InputStreamReader isr = new InputStreamReader(process.getInputStream(), Charset.forName("GBK"));
            LineNumberReader lnr = new LineNumberReader(isr);
            String line="";
            while((line = lnr.readLine()) != null)
            	stList.add(line);
            lnr.close();
            isr.close();
            
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage()+file.getAbsolutePath());
		}
		st = StringUtils.join(stList, "<br>");
		logger.info("文件："+filePath+" 结果："+st);
		return st;
	}
}
